package libcore.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import extension.dp

class CustomView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    //    private var paint: Paint = Paint()
    val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    // 斜线
    val path: Path = Path()

    // 圆弧
    val path2: Path = Path()

    init {
        paint.color = Color.BLUE
//        paint.textSkewX = -1f
        paint.textSize = 15.dp.toFloat()
//        path.addArc(50f, 750f, 300f, 900f, 0f, 180f)
        path.addOval(50f, 50f, 300f, 200f, Path.Direction.CW)
    }

    private var lastX = 0f
    private var lastY = 0f
    private var moveX = 0f
    private var moveY = 0f

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val action = event.action
        when (action) {
            MotionEvent.ACTION_DOWN -> {
                lastX = event.x
                lastY = event.y
                move = 0f
            }
            MotionEvent.ACTION_MOVE -> {
//                moveX = event.x - lastX
//                moveY = event.y - lastY
                lastX = event.x
                lastY = event.y
                move = event.x - lastX
                offset += move
                selectedValue = min + offset / lineSpace
                invalidate()
            }
        }
        return true
    }

    // 刻度间隔10dp，范围100-200，per = 1,共100条
    private var min = 100f
    private var max = 200f
    private var lineSpace = 10.dp.toFloat()
    private var midPoint = 0f
    private var offset = 0f
    private var move = 0f
    private var selectedValue = 150f

    init {
        offset = (selectedValue - min) * lineSpace
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        lastX = w / 2f
        lastY = h / 2f
        midPoint = w / 2f
    }

    override fun onDraw(canvas: Canvas) {
//        canvas.drawLine(0f, height / 2f, width.toFloat(), height / 2f, paint)
        var start: Float
        for (i in 0..100) {
            start = min + i * lineSpace - offset
            if (start < 0 || start > width) {
                continue  //  先画默认值在正中间，左右各一半的view。  多余部分暂时不画(也就是从默认值在中间，画旁边左右的刻度线)
            }

        }
//        canvas.save()

//        canvas.drawText("hello", lastX, lastY, paint)

//        path2.apply {
//            moveTo(width / 2f, height / 2f)
//            lineTo(width.toFloat(), 0f)
//        }

//        canvas.drawTextOnPath("What are you doing", path, 10f, 10f, paint)
//        canvas.drawTextOnPath("What are you doing", path2, 0f, 0f, paint)
    }
}